package io.task.cc.network.utils;

import io.task.cc.network.ChannelContext;
import io.task.cc.network.CloseCode;
import io.task.cc.network.Io;
import io.task.cc.network.utils.thread.ThreadUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Getter
public class IoUtils {

    public static boolean checkBeforeIO(ChannelContext channelContext) {
        if (channelContext.isWaitingClose) {
            return false;
        }

        Boolean isOpen = null;
        if (channelContext.asynchronousSocketChannel == null) {
            log.error("{}, 请检查此异常, asynchronousSocketChannel is null, isClosed:{}, isRemoved:{}, {} ", channelContext, channelContext.isClosed, channelContext.isRemoved,
                    ThreadUtils.stackTrace());
            return false;
        } else {
            isOpen = channelContext.asynchronousSocketChannel.isOpen();
            if (!isOpen) {
                log.info("{}, 可能对方关闭了连接, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isOpen, channelContext.isClosed, channelContext.isRemoved);
                Io.close(channelContext, "asynchronousSocketChannel is not open, 可能对方关闭了连接", CloseCode.CHANNEL_NOT_OPEN);
                return false;
            }
            //open
            if (channelContext.isClosed || channelContext.isRemoved) {
                try {
                    Io.close(channelContext,
                            "asynchronousSocketChannel is open, but channelContext isClosed: " + channelContext.isClosed + ", isRemoved: " + channelContext.isRemoved, CloseCode.CHANNEL_NOT_OPEN);
                } catch (Throwable e) {
                    log.error(e.toString(), e);
                }
                log.info("{}, isopen:{}, isClosed:{}, isRemoved:{}", channelContext, isOpen, channelContext.isClosed, channelContext.isRemoved);
                return false;
            }
            return true;
        }

    }

}
